package yartiss.engine.simulation.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import yartiss.engine.simulation.system.ITask;
import yartiss.engine.simulation.system.SystemMetrics;
import yartiss.engine.simulation.system.schedulable.GraphTask;
import yartiss.engine.simulation.system.schedulable.SimpleTask;
import yartiss.engine.simulation.system.schedulable.SubTask;

public class TextWriter implements ITaskElementVisitor {

	private final Writer writer;

	public TextWriter(String fileName, int nbTaskset, int nbTasks) throws IOException {
		this(new FileOutputStream(fileName), nbTaskset, nbTasks);
	}

	public TextWriter(File outFile, int nbTaskset, int nbTasks) throws IOException {
		this(new FileOutputStream(outFile), nbTaskset, nbTasks);
	}

	public TextWriter(OutputStream out, int nbTaskset, int nbTasks) throws IOException {
		writer = new OutputStreamWriter(out);
		writer.write("nbTasksets "+nbTaskset+ " nbTasks "+ nbTasks +"\n");
	}

	@Override
	public void visitTaskset(ITask[] taskset, int pr) throws IOException {

		writer.write(pr + " " + SystemMetrics.utilisation(taskset) + " "
				+ SystemMetrics.energyUtilization(taskset, pr) + "\n");
		for (ITask task : taskset) {
			if (task instanceof ITaskElement) {
				((ITaskElement) task).accept(this);
			}
		}
		writer.flush();
	}

	@Override
	public void visitGraphTask(GraphTask graph) {
		// TODO Auto-generated method stub

	}

	@Override
	public void visitSimpleTask(SimpleTask task) throws IOException {
		writer.write("type : " + task.getType() + " firstrelease : "
				+ task.getFirstRelease() + " wcet : " + task.getWcet()
				+ " wcee : " + task.getWcee() + " period : " + task.getPeriod()
				+ " deadline : " + task.getDeadline() + " priorirty : "
				+ task.getPriority() + "\n");
	}

	public void close() {
		try {
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void visitSubTask(SubTask subTask) {
		// TODO Auto-generated method stub

	}
}
